package com.globallogic.dailyplanner.jsfbeans;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.service.LoginService;
import com.globallogic.dailyplanner.service.UserService;

@Controller
@ManagedBean
public class ProfileBean {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private LoginService LoginService;
	
	@Autowired
	private ShaPasswordEncoder encoder;
	
	private User authUser;
	private String confirmPassword;
	
	public void init() {
		authUser = userService.findOneByName(LoginService.getAuthUsername());
	}
	
	public void isPasswordCorrect(FacesContext ctx, UIComponent component, Object value)
														throws ValidatorException{
		
		String confirmPassword = encoder.encodePassword(value.toString(), "");
		
		if (!confirmPassword.equals(authUser.getPassword())){
			FacesMessage message = new FacesMessage("Password is incorrect");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
	}
	
	public void deleteAccount(){
		if(authUser != null) {
			userService.kill(authUser.getId());
		}
	    SecurityContextHolder.getContext().setAuthentication(null);
	    SecurityContextHolder.clearContext();

	    try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public User getAuthUser() {
		return authUser;
	}

	public void setAuthUser(User authUser) {
		this.authUser = authUser;
	}
	
	public void edit(){
		userService.save(authUser);
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}
	
}
